package institution_service

import (
	"errors"

	"github.com/EDDYCJY/go-gin-example/models"
	"github.com/EDDYCJY/go-gin-example/pkg/util"
)

type GetSubAccount struct {
	InstitutionID int
	PageNum       int
	PageSize      int
}

func (t *GetSubAccount) GetSubAccount() (interface{}, error) {
	maps := map[string]interface{}{
		"institution_id": t.InstitutionID,
	}
	total, _ := models.GetUserTotal(maps)
	goodsList, _ := models.GetUserPage([]string{"user_id", "user_name"}, maps, t.PageNum, t.PageSize, "")
	var lists []interface{}
	for _, v := range goodsList {
		params := map[string]interface{}{
			"user_id":   v.UserId,
			"user_name": v.UserName,
		}
		lists = append(lists, params)
	}
	return map[string]interface{}{
		"lists": lists,
		"total": total,
	}, nil
}

// Login 定义登录请求结构体
type AddSubAccount struct {
	InstitutionID int
	UserName      string `alias:"用户名" form:"user_name"  json:"user_name" valid:"Required;"`
	UserPassword  string `alias:"密码" form:"user_password"  json:"user_password" valid:"Required;"`
	UserID        int
}

// AddSubAccount 执行用户登录逻辑
func (t *AddSubAccount) AddSubAccount() (map[string]interface{}, error) {
	var maps = map[string]interface{}{
		"institution_id": t.InstitutionID,
		"user_name":      t.UserName,
	}
	userInfo, _ := models.GetUserInfo([]string{"user_id"}, maps)
	if userInfo.UserId != 0 {
		return nil, errors.New("用户已存在")
	}
	maps["user_password"] = util.EncodeMD5(t.UserPassword)
	_, err := models.AddUser(maps)
	if err != nil {
		return nil, err
	}
	return nil, nil
}

// Login 定义登录请求结构体
type EditSubAccount struct {
	UserID        int
	InstitutionID int
	UserPassword  string
}

// EditSubAccount 执行用户登录逻辑
func (t *EditSubAccount) EditSubAccount() (map[string]interface{}, error) {

	var maps = map[string]interface{}{
		"institution_id": t.InstitutionID,
		"user_id":        t.UserID,
	}
	var update = map[string]interface{}{
		"user_password": util.EncodeMD5(t.UserPassword),
	}
	err := models.EditUser(maps, update)
	if err != nil {
		return nil, err
	}
	return nil, nil
}

// Login 定义登录请求结构体
type DeleteSubAccount struct {
	UserID        int
	InstitutionID int
}

// DeleteSubAccount 执行用户登录逻辑
func (t *DeleteSubAccount) DeleteSubAccount() (map[string]interface{}, error) {
	var maps = map[string]interface{}{
		"institution_id": t.InstitutionID,
		"user_id":        t.UserID,
	}
	err := models.CleanUser(maps)
	if err != nil {
		return nil, err
	}
	return nil, nil
}
